﻿using System.Web;
using InterpriseSuiteEcommerceCommon.Extensions;
using System.IO;
using System.Linq;

namespace InterpriseSuiteEcommerceCommon.Tool
{
    public static class CurrentContext
    {
        public static string ToValue(string key)
        {
            string value = string.Empty;
            if (HttpContext.Current == null) throw new HttpException("Invalid Current Context");

            value = HttpContext.Current.Items[key] as string;
            return value;
        }

        public static bool IsRequestingFromMobileBrowser()
        {
            return !ToValue(DomainConstants.DeviceTypeName).IsNullOrEmptyTrimmed();
        }

        public static bool IsRequestingFromMobileMode(Customer thisCustomer)
        { 
            bool isRequestingFullMode = false;
            if (thisCustomer != null)
            {
                isRequestingFullMode = thisCustomer.FullModeInMobile;
            }

            return IsRequestingFromMobileBrowser() && !isRequestingFullMode;
        }

        public static void Add<T>(string key, T item)
        {
            if (HttpContext.Current == null) throw new HttpException("Invalid Current Context");

            HttpContext.Current.Items.Add(key, item);
        }

        public static void Remove(string key)
        {
            if (HttpContext.Current == null) throw new HttpException("Invalid Current Context");

            HttpContext.Current.Items.Remove(key);
        }

        //This Function will verify if the request is from mobile Folder
        //and verify if the Mobile.Config exist in that folder.
        public static bool IsInMobilePages(string mobileFolderName)
        {
            bool inMobilePages = false;

            if (HttpContext.Current == null) throw new HttpException("Invalid Current Context");

            string pathorfile = HttpContext.Current.Request.PhysicalPath.ToLowerInvariant();
            string currentRequestExecutionFolder = pathorfile.ToPathFromFileOrPath();
            bool isWorkingInMobileFolder = currentRequestExecutionFolder.Contains(mobileFolderName.ToLowerInvariant());

            if (isWorkingInMobileFolder)
            {
                try
                {
                    var files = Directory.GetFiles(currentRequestExecutionFolder);
                    bool isMobileConfigExist = files.Any(f => f.ToLowerInvariant().Contains("mobile.config"));
                    if (isMobileConfigExist)
                    {
                        inMobilePages = isMobileConfigExist;
                        AppStartLogger.WriteLine("Mobile.config exist");
                    }
                    else
                    {
                        AppStartLogger.WriteLine("Mobile.config does not exist");
                    }
                }
                catch (DirectoryNotFoundException)
                {
                    AppStartLogger.WriteLine("Folder or file does not exist: " + currentRequestExecutionFolder);
                }
            }
            else
            {
                inMobilePages = false;
                AppStartLogger.WriteLine("Not in mobile folder: " + currentRequestExecutionFolder);
            }

            return inMobilePages;
        }

        public static bool IsInRoot()
        {
            if (HttpContext.Current == null) throw new HttpException("Invalid Current Context");

            string rootPath = HttpContext.Current.Request.PhysicalApplicationPath;
            string currentPath = HttpContext.Current.Request.PhysicalPath.ToPathFromFileOrPath(true);
            return (rootPath.Equals(currentPath));
        }

        public static bool IsInAdminRoot()
        {
            if (HttpContext.Current == null) throw new HttpException("Invalid Current Context");

            string adminRootPath = HttpContext.Current.Request.PhysicalApplicationPath + "admin\\";
            string currentPath = HttpContext.Current.Request.PhysicalPath.ToPathFromFileOrPath(true);
            return (adminRootPath.Equals(currentPath));
        }

        public static bool IsRequestFromWebservice()
        {
            if (HttpContext.Current == null) throw new HttpException("Invalid Current Context");

            string path = HttpContext.Current.Request.PhysicalPath;
            return path.EndsWith(".asmx") || path.EndsWith(".axd");
        }

        public static bool IsRequestFromResources()
        {
            if (HttpContext.Current == null) throw new HttpException("Invalid Current Context");

            string path = HttpContext.Current.Request.PhysicalPath;
            return path.EndsWith(".axd");
        }

        public static bool IsRequestingFullModeFromMobile(Customer currentCustomer)
        {
            bool returnValue = false;

            if (currentCustomer == null) return returnValue;

            bool? currentCustomerRequest = currentCustomer.ThisCustomerSession[DomainConstants.MOBILE_FULLMODE_QUERYTSTRING].TryParseBool();

            bool? isRequestedFullMode = DomainConstants.MOBILE_FULLMODE_QUERYTSTRING.ToQueryString().TryParseBool();

            //query string has true value
            if (isRequestedFullMode.HasValue && isRequestedFullMode.Value)
            {
                currentCustomer.ThisCustomerSession[DomainConstants.MOBILE_FULLMODE_QUERYTSTRING] = true.ToString();
                returnValue = true;
            }
            //query string has false value
            else if (isRequestedFullMode.HasValue && !isRequestedFullMode.Value)
            {
                currentCustomer.ThisCustomerSession[DomainConstants.MOBILE_FULLMODE_QUERYTSTRING] = false.ToString();
                returnValue = false;
            }
            //no querystring but customer already set
            else if (currentCustomerRequest.HasValue && currentCustomerRequest.Value)
            {
                returnValue = true;
            }
            //query string not set and customer not set
            else
            {
                returnValue = false;
            }

            return returnValue;
        }

        public static bool IsDownLoadPage()
        {
            if (HttpContext.Current == null) throw new HttpException("Invalid Current Context");
            return HttpContext.Current.Request.PhysicalPath.Contains("download.aspx");
        }

        public static string ApplicationPath()
        {
            return HttpContext.Current.Request.ApplicationPath;
        }

        public static void RedirectToMobileDownloadPage()
        {
            string param = string.Empty;
            if (HttpContext.Current.Request.QueryString.Count > 0)
            {
                var arrayValueParam = HttpContext.Current.Request.QueryString.ToPairs().Select(item => item.Key + "=" + item.Value).ToArray();
                param = string.Format("?{0}", string.Join("&", arrayValueParam));
            }
            HttpContext.Current.Response.Redirect("mobile/download.aspx" + param);
        }

        public static bool IsRequestFromGoogleCheckout()
        {
            string userAgent = HttpContext.Current.Request.ServerVariables[DomainConstants.HTTP_USER_AGENT].ToLowerInvariant();
            return userAgent.Contains("google checkout");
        }

        public static bool IsMobileFolderExist()
        {
            return Directory.Exists(HttpContext.Current.Request.PhysicalApplicationPath + "\\Mobile");
        }

        public static void GoPageNotFound()
        {
            HttpContext.Current.Response.Redirect("t-error404.aspx");
        }

        public static string UserHostName()
        {
            return HttpContext.Current.Request.UserHostName;
        }

        public static string Scheme()
        {
            return HttpContext.Current.Request.Url.Scheme;
        }

        public static string FullyQualifiedApplicationPath()
        {
            //Return variable declaration
            string appPath = null;

            //Getting the current context of HTTP request
            var context = HttpContext.Current;

            //Checking the current context content
            if (context != null)
            {
                //Formatting the fully qualified website url/name
                appPath = string.Format("{0}://{1}{2}{3}",
                                        context.Request.Url.Scheme,
                                        context.Request.Url.Host,
                                        context.Request.Url.Port == 80
                                            ? string.Empty
                                            : ":" + context.Request.Url.Port,
                                        context.Request.ApplicationPath);
            }

            if (!appPath.EndsWith("/"))
                appPath += "/";

            return appPath;
        }

        public static void Redirect(string url)
        {
            HttpContext.Current.Response.Redirect(url);
        }

        public static string MapPath(string path)
        {
            if (HttpContext.Current != null)
                return HttpContext.Current.Server.MapPath(path);

            return HttpRuntime.AppDomainAppPath + path.Replace("~", string.Empty).Replace('/', '\\');
        }
    }
}